package com.globallogic.qdumper;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.globallogic.qdumper.bean.QueryItem;

public class FileService
{
    public List<QueryItem> getQueryItems(String directory)
    {
        List<QueryItem> queryItems = new ArrayList<QueryItem>();

        List<File> sqlFiles = getSqlFiles(directory);
        for ( File file : sqlFiles )
        {
            QueryItem queryItem = new QueryItem();
            queryItem.setQueryFileName(file.getName());

            try
            {
                queryItem.setQueryText(readContent(file));
            }
            catch ( Exception e )
            {
                e.printStackTrace();
            }
            queryItems.add(queryItem);
        }

        return queryItems;
    }

    private String readContent(File file) throws FileNotFoundException, IOException
    {
        BufferedReader reader = new BufferedReader(new FileReader(file));

        StringBuffer sb = new StringBuffer();
        String eachLine = reader.readLine();

        while ( eachLine != null )
        {
            sb.append(eachLine);
            sb.append("\n");
            eachLine = reader.readLine();
        }
        return sb.toString();
    }

    public List<File> getSqlFiles(String directory)
    {
        File dir = new File(directory);

        List<File> sqlFiles = new ArrayList<File>();

        File[] listFiles = dir.listFiles(sqlFilter);
        if ( listFiles != null )
        {
            Collections.addAll(sqlFiles, listFiles);
        }

        System.out.println("Found " + sqlFiles.size() + " sql files in " + directory);
        return sqlFiles;
    }

    private final static FilenameFilter sqlFilter = new FilenameFilter()
            {
        public boolean accept(File dir, String name)
                {
            return name.endsWith(".sql");
        }

    };

    public void flushResults(List<QueryItem> queryItems, String xmlDir) throws Exception
    {
        for ( QueryItem queryItem : queryItems )
        {
            File file = new File(xmlDir + "/" + queryItem.getResultFileName());

            FileWriter fileWriter = new FileWriter(file);

            try
            {
                fileWriter.write(queryItem.getResultText());
            }
            finally
            {
                fileWriter.close();
            }
        }
    }
}
